package com.gpj.learn.rabbitmq.dlx;

import com.gpj.learn.rabbitmq.common.CommonConstants;
import com.gpj.learn.rabbitmq.common.RabbitUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @className PubSubProducer
 * @description
 *   TODO
 * @author GPJ
 * @date 2021/5/30 12:33
 * @version 1.0
 **/
@Slf4j
public class DLXProducer {
	public static void main(String[] args) throws IOException {
		log.info("------------- 开始发送消息 -------------");
		Channel channel = RabbitUtil.createChannel();

		// 声明一个死信队列
		channel.queueDeclare(CommonConstants.RABBITMQ_QUEUE_DLX_DEADLETTER,
				false, false, false, null);
		// 声明一个死信交换机
		channel.exchangeDeclare(CommonConstants.RABBITMQ_EXCHANGE_DLX_DEADLETTER,
				BuiltinExchangeType.DIRECT, false, false, false, null);

		// 声明一个正常队列
		Map<String, Object> map = new HashMap<>();
		// 绑定正常队列与死信交换机
		map.put("x-dead-letter-exchange", CommonConstants.RABBITMQ_EXCHANGE_DLX_DEADLETTER);
		map.put("x-dead-letter-routing-key", "dlx.msg");
		channel.queueDeclare(CommonConstants.RABBITMQ_QUEUE_DLX_NORMAL,
				false, false, false, map);
		// 声明一个正常交换机
		channel.exchangeDeclare(CommonConstants.RABBITMQ_EXCHANGE_DLX_NORMAL,
				BuiltinExchangeType.DIRECT, false, false, false, null);

		// 绑定正常队列与正常交换机
		channel.queueBind(
				CommonConstants.RABBITMQ_QUEUE_DLX_NORMAL, // 队列名
				CommonConstants.RABBITMQ_EXCHANGE_DLX_NORMAL, // 交换机名
				"test.dlx"); // 路由key

		// 绑定死信队列与死信交换机
		channel.queueBind(
				CommonConstants.RABBITMQ_QUEUE_DLX_DEADLETTER, // 队列名
				CommonConstants.RABBITMQ_EXCHANGE_DLX_DEADLETTER, // 交换机名
				"dlx.msg"); // 路由key

		// 发送消息
		String meaasge = "dlx message no.";
		AMQP.BasicProperties properties = new AMQP.BasicProperties().builder().expiration("6000").build();
		channel.basicPublish(CommonConstants.RABBITMQ_EXCHANGE_DLX_NORMAL,
				"test.dlx", properties, (meaasge + 1).getBytes());
		RabbitUtil.close(channel);
		log.info("------------- 消息发送完成 -------------");
	}
}
